import { Component, OnInit, Input } from '@angular/core';
import { Hero } from '../hero';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { HeroService } from '../hero.service';
import { MessageService } from '../message.service';

@Component({
    selector: 'app-hero-detail',
    templateUrl: './hero-detail.component.html',
    styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {
    @Input()
    hero: Hero;

    constructor(
        private route: ActivatedRoute,
        private location: Location,
        private heroService: HeroService,
        private messageService: MessageService
    ) { }

    ngOnInit() {
        const id = +this.route.snapshot.paramMap.get('id');
        this.heroService
            .getHeroAsync(id)
            .subscribe(t => {
                if (!t) {
                    this.messageService.add(`不存在编号为${id}的英雄`);
                }
                this.hero = t;
            });
    }

    /**
     * 返回
     */
    goBack() {
        this.location.back();
    }

    update() {
        this.heroService
            .updateHeorAsync(this.hero)
            .subscribe((_) => {
                this.goBack();
            });
    }



}
